const state = {
  items: [],
  maxItems: 1000,
  filters: {
    type: 'all',
    searchText: ''
  }
}

const mutations = {
  ADD_ITEM(state, item) {
    state.items.unshift({
      ...item,
      id: `history_${Date.now()}`,
      timestamp: new Date().toISOString()
    })
    if (state.items.length > state.maxItems) {
      state.items = state.items.slice(0, state.maxItems)
    }
  },
  
  REMOVE_ITEM(state, id) {
    state.items = state.items.filter(item => item.id !== id)
  },
  
  CLEAR_HISTORY(state) {
    state.items = []
  },
  
  SET_FILTER(state, { key, value }) {
    state.filters[key] = value
  }
}

const getters = {
  filteredItems: (state) => {
    let items = state.items
    
    if (state.filters.type !== 'all') {
      items = items.filter(item => item.type === state.filters.type)
    }
    
    if (state.filters.searchText) {
      const searchLower = state.filters.searchText.toLowerCase()
      items = items.filter(item => {
        const searchableText = `${item.url || ''} ${item.method || ''} ${item.topic || ''}`.toLowerCase()
        return searchableText.includes(searchLower)
      })
    }
    
    return items
  }
}

const actions = {
  addItem({ commit }, item) {
    commit('ADD_ITEM', item)
  },
  
  removeItem({ commit }, id) {
    commit('REMOVE_ITEM', id)
  },
  
  clearHistory({ commit }) {
    commit('CLEAR_HISTORY')
  },
  
  setFilter({ commit }, filter) {
    commit('SET_FILTER', filter)
  },
  
  saveHistory({ state }) {
    localStorage.setItem('linkverify-history', JSON.stringify(state.items.slice(0, 100)))
  },
  
  loadHistory({ commit }) {
    const saved = localStorage.getItem('linkverify-history')
    if (saved) {
      try {
        const items = JSON.parse(saved)
        items.forEach(item => commit('ADD_ITEM', item))
      } catch (e) {
        console.error('Failed to load history:', e)
      }
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  getters,
  actions
}